package com.dmooo.yxmmerchant.view.ui;

import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TextInputEditText;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioGroup;

import com.common.dialog.ZDYDialog;
import com.common.dialog.ZDYTipDialog;
import com.common.util.LogUtil;
import com.common.util.SPUtils;
import com.common.util.StartActivityUtil;
import com.common.util.ToastUtil;
import com.common.wx.HttpUtils;
import com.dmooo.yxmmerchant.MainActivity;
import com.dmooo.yxmmerchant.R;
import com.dmooo.yxmmerchant.base.BaseActivity;
import com.dmooo.yxmmerchant.common.Config;
import com.dmooo.yxmmerchant.util.ListDataSave;
import com.dmooo.yxmmerchant.view.contract.LoginContract;
import com.dmooo.yxmmerchant.view.model.AccPass;
import com.dmooo.yxmmerchant.view.presenter.LoginPrestener;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cz.msebera.android.httpclient.Header;

public class LoginActivity extends BaseActivity<LoginPrestener> implements LoginContract.LoginView {
    @BindView(R.id.et_account)
    TextInputEditText etPhone;
    @BindView(R.id.et_psd)
    TextInputEditText etPwd;
    ZDYTipDialog tipDialog;
    ZDYDialog zdyDialog;
    @BindView(R.id.rg_type)
    RadioGroup rgType;
    @BindView(R.id.ll_main)
    LinearLayout llMain;
    @BindView(R.id.et_account2)
    TextInputEditText etAccount2;
    @BindView(R.id.et_main)
    TextInputEditText etMain;
    @BindView(R.id.et_psd2)
    TextInputEditText etPsd2;
    @BindView(R.id.ll_child)
    LinearLayout llChild;

    ListDataSave dataSave;
    private List<Object> listBean;
    AccPass user;


    @Override
    protected int getLayout() {
        return R.layout.activity_login;
    }

    @Override
    protected void initEventAndData() {
        dataSave = new ListDataSave(LoginActivity.this, "baiyu");
        listBean = new ArrayList<>();

        tipDialog = new ZDYTipDialog(this, "正在登录中", "知道了", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tipDialog.dismiss();
            }
        });
        rgType.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if(checkedId==R.id.rb_one){
                    llMain.setVisibility(View.VISIBLE);
                    llChild.setVisibility(View.GONE);
                }else{
                    llMain.setVisibility(View.GONE);
                    llChild.setVisibility(View.VISIBLE);
                }
            }
        });
        if("1".equals(SPUtils.get(this,Config.LOGIN_TYPE,"1"))){
            etPhone.setText(SPUtils.get(this, Config.PHONE, "").toString());
            etPwd.setText(SPUtils.get(this, Config.PWD, "").toString());
            if (!"".equals(etPwd.getText().toString())) {
                etPwd.requestFocus();
                etPwd.setSelection(etPwd.getText().length());
            }
        }else{
            rgType.check(R.id.rb_two);
            if(getIntent().getStringExtra("acount")!=null){
                etAccount2.setText(getIntent().getStringExtra("acount"));
                etMain.setText(getIntent().getStringExtra("mername"));
                etPsd2.setText(getIntent().getStringExtra("password"));
            }else{
                etMain.setText(SPUtils.get(this, Config.LOGIN_ACCOUNT, "").toString());
                etAccount2.setText(SPUtils.get(this, Config.MERCHANT_NAME, "").toString());
                etPsd2.setText(SPUtils.get(this, Config.PWD, "").toString());
            }
            if (!"".equals(etPsd2.getText().toString())) {
                etPsd2.requestFocus();
                etPsd2.setSelection(etPsd2.getText().length());
            }
        }
    }

    @Override
    protected void createPresenter() {
        mPresenter = new LoginPrestener(this, this);
    }

    @Override
    public void loginSuccess() {
        loginHandle.sendEmptyMessage(0);
    }

    private void loginHuanxin() {
        EMClient.getInstance().login(SPUtils.get(this, Config.ADMIN_ID, "").toString(), "123456", new EMCallBack() {//回调
            @Override
            public void onSuccess() {
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();
                SPUtils.put(LoginActivity.this,Config.LOGIN_TYPE,"2");
                LogUtil.d("main", "登录聊天服务器成功！");
                StartActivityUtil.startActivity(LoginActivity.this, MainActivity.class);
                user = new AccPass();
                listBean=dataSave.getDataList("javaBean");
                if(listBean.size()>0){
                    for(int i=0;i<listBean.size();i++){
                        if(listBean.get(i).toString().contains(etMain.getText().toString())){
                            finish();
                            return;
                        }
                    }
                    user.setMername(etMain.getText().toString());
                    user.setAccount(etAccount2.getText().toString());
                    user.setPassword(etPsd2.getText().toString());
                    listBean.add(user);
                    dataSave.setDataList("javaBean",listBean);
                }else{
                    user.setMername(etMain.getText().toString());
                    user.setAccount(etAccount2.getText().toString());
                    user.setPassword(etPsd2.getText().toString());
                    listBean.add(user);
                    dataSave.setDataList("javaBean",listBean);
                }
                finish();
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(int code, String message) {
                LogUtil.d("main", "登录聊天服务器失败！" + message);
                if(message.contains("already login")){
                    EMClient.getInstance().logout(true);
//                    loginHandle.sendEmptyMessage(0);
                }else{
                    handler.sendEmptyMessage(0);
                }
            }
        });
    }

    private Handler loginHandle=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            loginHuanxin();
        }
    };
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            createChat();
        }
    };
    private void createChat() {
        RequestParams params = new RequestParams();
        params.put("token", SPUtils.get(this, Config.TOKEN, "").toString());
        HttpUtils.post(Config.APP_INTERFACE_BASE_URL+"/app.php?c=Huanxin&a=createUser", params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                // 输出错误信息
//                LogUtils.e(TAG, "onFailure()--" + responseString);
            }

            @Override
            public void onFinish() {
                // 隐藏进度条
                super.onFinish();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                Log.d("dfasdfsaf",responseString);
                try {
                    JSONObject jsonObject = new JSONObject(responseString);
                    if(jsonObject.getInt("code")!=0){
                        ToastUtil.getInstance().showErrorMsg("登录聊天服务器失败");
                    }else{
                        loginHandle.sendEmptyMessage(0);
                    }
//                    //返回码
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onStart() {
                // 显示进度条
                super.onStart();
            }
        });
    }


    @OnClick({R.id.txt_forget, R.id.tv_login, R.id.tv_register})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.txt_forget:
                StartActivityUtil.startActivity(this, ForgetPwdActivity.class);
                break;
            case R.id.tv_login:
//                if(rgType.getCheckedRadioButtonId()==R.id.rb_one){
//                    if (TextUtils.isEmpty(etPhone.getText().toString())) {
//                        ToastUtil.getInstance().showErrorMsg("请输入登录账号");
//                        return;
//                    }
//                    if (TextUtils.isEmpty(etPwd.getText().toString())) {
//                        ToastUtil.getInstance().showErrorMsg("请输入登录密码");
//                        return;
//                    }
//                    mPresenter.doLogin(etPhone.getText().toString(), etPwd.getText().toString());
//                }else{
                    if (TextUtils.isEmpty(etMain.getText().toString())) {
                        ToastUtil.getInstance().showErrorMsg("请输入商户信息");
                        return;
                    }
                    if (TextUtils.isEmpty(etAccount2.getText().toString())) {
                        ToastUtil.getInstance().showErrorMsg("请输入登录账号");
                        return;
                    }
                    if (TextUtils.isEmpty(etPsd2.getText().toString())) {
                        ToastUtil.getInstance().showErrorMsg("请输入登录密码");
                        return;
                    }
                    mPresenter.doLoginAdmin(etMain.getText().toString(),etAccount2.getText().toString(), etPsd2.getText().toString());
//                }
                break;
            case R.id.tv_register:
                StartActivityUtil.startActivity(this, RegisterActivity.class);
                break;
        }
    }
}
